package com.sav.common.dao;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

import javax.sql.DataSource;

import com.mysql.jdbc.Statement;

public class BaseDAO {
	
	private static Connection connection = null;

	public void setDataSource(DataSource dataSource) {
		try {
			if (connection == null) connection = dataSource.getConnection();
		} catch (SQLException e) {
			e.printStackTrace();
		}
	}
	
	public Connection getConnection() {
		return connection;
	}
	
	public PreparedStatement createStatementForInsert(String query) {
		PreparedStatement stm = null;
		try {
			stm = getConnection().prepareStatement(query, Statement.RETURN_GENERATED_KEYS);
		} catch (SQLException e) {
			e.printStackTrace();
		}
		return stm;
	}
	
	public int executeInsert(PreparedStatement stm) {
		int newId = 0;
		try {
			stm.executeUpdate();
			ResultSet rs = stm.getGeneratedKeys();
			if (rs.next()){
				newId = rs.getInt(1);
			}
			rs.close();
		} catch (SQLException e) {
			e.printStackTrace();
		} finally {
			try {
				stm.close();
			} catch (SQLException e) {
				e.printStackTrace();
			}
		}
		
		return newId;
	}

}
